import React, { useState, useCallback, useRef, useEffect } from 'react';
import { DndProvider, useDrag, useDrop } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import { create } from 'zustand';
// import { debounce } from 'lodash';
import {
  Button,
  Input,
  Card,
  Select,
  Switch,
  Slider,
  ColorPicker,
  Form,
  InputNumber,
  Typography,
  Space,
  Divider,
  Tabs,
  Modal,
  message,
  Tooltip
} from 'antd';
import {
  PlusOutlined,
  DeleteOutlined,
  CopyOutlined,
  CodeOutlined,
  SettingOutlined,
  EyeOutlined,
  SaveOutlined,
  BgColorsOutlined,
  DragOutlined,
  AppstoreOutlined,
  LayoutOutlined,
  MenuOutlined,
  EditOutlined
} from '@ant-design/icons';

const { Title, Text } = Typography;
const { Option } = Select;

// Zustand 状态管理
const useStore = create((set, get) => ({
  components: [],
  selectedComponent: null,
  draggedComponent: null,

  addComponent: (component) => {
    const newComponent = {
      ...component,
      id: `${component.type}_${Date.now()}`,
      style: {
        position: 'absolute',
        left: component.x || 100,
        top: component.y || 100,
        zIndex: 1,
        ...component.style
      }
    };
    set(state => ({
      components: [...state.components, newComponent]
    }));
  },

  updateComponent: (id, updates) => {
    set(state => ({
      components: state.components.map(comp =>
        comp.id === id ? { ...comp, ...updates } : comp
      )
    }));
  },

  deleteComponent: (id) => {
    set(state => ({
      components: state.components.filter(comp => comp.id !== id),
      selectedComponent: state.selectedComponent?.id === id ? null : state.selectedComponent
    }));
  },

  selectComponent: (component) => {
    set({ selectedComponent: component });
  },

  setDraggedComponent: (component) => {
    set({ draggedComponent: component });
  },

  duplicateComponent: (id) => {
    const state = get();
    const component = state.components.find(comp => comp.id === id);
    if (component) {
      const newComponent = {
        ...component,
        id: `${component.type}_${Date.now()}`,
        style: {
          ...component.style,
          left: component.style.left + 20,
          top: component.style.top + 20
        }
      };
      set(state => ({
        components: [...state.components, newComponent]
      }));
    }
  },

  clearCanvas: () => {
    set({
      components: [],
      selectedComponent: null
    });
  }
}));

// 组件类型定义
const COMPONENT_TYPES = {
  BUTTON: 'button',
  INPUT: 'input',
  TEXT: 'text',
  CARD: 'card',
  SELECT: 'select',
  SWITCH: 'switch',
  SLIDER: 'slider'
};

// 组件库
const ComponentLibrary = [
  {
    type: COMPONENT_TYPES.BUTTON,
    name: '按钮',
    icon: '🔘',
    defaultProps: {
      text: '按钮',
      type: 'primary',
      size: 'middle'
    },
    style: {
      width: 80,
      height: 32
    }
  },
  {
    type: COMPONENT_TYPES.INPUT,
    name: '输入框',
    icon: '📝',
    defaultProps: {
      placeholder: '请输入内容',
      value: ''
    },
    style: {
      width: 200,
      height: 32
    }
  },
  {
    type: COMPONENT_TYPES.TEXT,
    name: '文本',
    icon: '📄',
    defaultProps: {
      text: '文本内容',
      level: 4
    },
    style: {
      width: 100,
      height: 24
    }
  },
  {
    type: COMPONENT_TYPES.CARD,
    name: '卡片',
    icon: '🃏',
    defaultProps: {
      title: '卡片标题',
      content: '卡片内容'
    },
    style: {
      width: 300,
      height: 200
    }
  },
  {
    type: COMPONENT_TYPES.SELECT,
    name: '选择器',
    icon: '📋',
    defaultProps: {
      placeholder: '请选择',
      options: [
        { value: 'option1', label: '选项1' },
        { value: 'option2', label: '选项2' }
      ]
    },
    style: {
      width: 200,
      height: 32
    }
  },
  {
    type: COMPONENT_TYPES.SWITCH,
    name: '开关',
    icon: '🔀',
    defaultProps: {
      checked: false
    },
    style: {
      width: 44,
      height: 22
    }
  },
  {
    type: COMPONENT_TYPES.SLIDER,
    name: '滑块',
    icon: '🎛️',
    defaultProps: {
      min: 0,
      max: 100,
      value: 50
    },
    style: {
      width: 200,
      height: 20
    }
  }
];

// 拖拽组件项
const DragItem = ({ component }) => {
  const [{ isDragging }, drag] = useDrag(() => ({
    type: 'component',
    item: component,
    collect: (monitor) => ({
      isDragging: monitor.isDragging(),
    }),
  }));

  return (
    <div
      ref={drag}
      style={{
        padding: '12px 16px',
        margin: '8px 0',
        backgroundColor: '#ffffff',
        border: '1px solid #e8e8e8',
        borderRadius: '8px',
        cursor: 'move',
        transition: 'all 0.2s ease',
        opacity: isDragging ? 0.6 : 1,
        display: 'flex',
        alignItems: 'center',
        gap: '12px',
        ':hover': {
          backgroundColor: '#f5f5f5',
          borderColor: '#667eea',
          transform: 'translateY(-1px)'
        }
      }}
      onMouseEnter={(e) => {
        e.currentTarget.style.backgroundColor = '#f8f9ff';
        e.currentTarget.style.borderColor = '#667eea';
        e.currentTarget.style.transform = 'translateY(-1px)';
      }}
      onMouseLeave={(e) => {
        if (!isDragging) {
          e.currentTarget.style.backgroundColor = '#ffffff';
          e.currentTarget.style.borderColor = '#e8e8e8';
          e.currentTarget.style.transform = 'translateY(0)';
        }
      }}
    >
      <span style={{ fontSize: '18px' }}>{component.icon}</span>
      <span style={{ fontSize: '13px', fontWeight: 500, color: '#2c3e50' }}>
        {component.name}
      </span>
    </div>
  );
};

// 渲染组件
const renderComponent = (component, isSelected, onClick) => {
  const commonProps = {
    key: component.id,
    style: {
      ...component.style,
      cursor: 'pointer',
      transition: 'all 0.2s ease'
    },
    onContextMenu: (e) => handleContextMenu(e, component),
    onMouseDown: (e) => {
      e.stopPropagation();
      onClick(component);
      handleMouseDown(e, component); // 新增拖拽处理
    },

  };
  const handleContextMenu = (e, component) => {
    e.preventDefault();
    // 这里可以显示右键菜单，包含复制、删除、置顶等操作
  };

  const selectedStyle = isSelected ? {
    ...commonProps.style,
    boxShadow: '0 0 0 2px #667eea, 0 0 0 4px rgba(102, 126, 234, 0.2)',
    borderRadius: '6px'
  } : commonProps.style;

  commonProps.style = selectedStyle;

  switch (component.type) {
    case COMPONENT_TYPES.BUTTON:
      return (
        <div {...commonProps}>
          <Button
            type={component.props.type}
            size={component.props.size}
            style={{
              width: component.style.width,
              height: component.style.height,
              borderRadius: '6px',
              fontWeight: 500
            }}
          >
            {component.props.text}
          </Button>
        </div>
      );

    case COMPONENT_TYPES.INPUT:
      return (
        <div {...commonProps}>
          <Input
            placeholder={component.props.placeholder}
            value={component.props.value}
            style={{
              width: component.style.width,
              height: component.style.height,
              borderRadius: '6px'
            }}
          />
        </div>
      );

    case COMPONENT_TYPES.TEXT:
      return (
        <div {...commonProps}>
          <Title level={component.props.level} style={{ margin: 0 }}>
            {component.props.text}
          </Title>
        </div>
      );

    case COMPONENT_TYPES.CARD:
      return (
        <div {...commonProps}>
          <Card
            title={component.props.title}
            style={{
              width: component.style.width,
              height: component.style.height,
              borderRadius: '8px',
              boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)'
            }}
          >
            {component.props.content}
          </Card>
        </div>
      );

    case COMPONENT_TYPES.SELECT:
      return (
        <div {...commonProps}>
          <Select
            placeholder={component.props.placeholder}
            style={{
              width: component.style.width,
              height: component.style.height
            }}
          >
            {component.props.options.map(option => (
              <Option key={option.value} value={option.value}>
                {option.label}
              </Option>
            ))}
          </Select>
        </div>
      );

    case COMPONENT_TYPES.SWITCH:
      return (
        <div {...commonProps}>
          <Switch
            checked={component.props.checked}
            style={{
              width: component.style.width,
              height: component.style.height
            }}
          />
        </div>
      );

    case COMPONENT_TYPES.SLIDER:
      return (
        <div {...commonProps}>
          <Slider
            min={component.props.min}
            max={component.props.max}
            value={component.props.value}
            style={{
              width: component.style.width,
              margin: '10px 0'
            }}
          />
        </div>
      );

    default:
      return null;
  }
};

// 属性编辑器
const PropertyEditor = ({ component, onUpdate }) => {
  if (!component) {
    return (
      <div style={{
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        height: '300px',
        color: '#999'
      }}>
        <EditOutlined style={{ fontSize: '48px', color: '#d9d9d9', marginBottom: '16px' }} />
        <Text style={{ color: '#999' }}>选择组件来编辑属性</Text>
      </div>
    );
  }
  // const debouncedUpdate = useMemo(
  //   () => debounce((field, value) => {
  //     // 原来的 handleUpdate 逻辑
  //   }, 300),
  //   [component, onUpdate]
  // );

  const handleUpdate = (field, value) => {
    if (field.startsWith('style.')) {
      const styleField = field.replace('style.', '');
      onUpdate(component.id, {
        style: {
          ...component.style,
          [styleField]: value
        }
      });
    } else if (field.startsWith('props.')) {
      const propField = field.replace('props.', '');
      onUpdate(component.id, {
        props: {
          ...component.props,
          [propField]: value
        }
      });
    }
  };

  return (
    <div style={{ padding: '0 4px' }}>
      <div style={{ marginBottom: '24px' }}>
        <Text strong style={{ color: '#2c3e50', fontSize: '14px' }}>位置和尺寸</Text>
        <div style={{
          marginTop: '12px',
          display: 'grid',
          gridTemplateColumns: '1fr 1fr',
          gap: '8px'
        }}>
          <div>
            <Text style={{ fontSize: '12px', color: '#666', display: 'block', marginBottom: '4px' }}>X坐标</Text>
            <InputNumber
              value={component.style.left}
              onChange={(value) => handleUpdate('style.left', value)}
              style={{ width: '100%' }}
              size="small"
            />
          </div>
          <div>
            <Text style={{ fontSize: '12px', color: '#666', display: 'block', marginBottom: '4px' }}>Y坐标</Text>
            <InputNumber
              value={component.style.top}
              onChange={(value) => handleUpdate('style.top', value)}
              style={{ width: '100%' }}
              size="small"
            />
          </div>
          <div>
            <Text style={{ fontSize: '12px', color: '#666', display: 'block', marginBottom: '4px' }}>宽度</Text>
            <InputNumber
              value={component.style.width}
              onChange={(value) => handleUpdate('style.width', value)}
              style={{ width: '100%' }}
              size="small"
            />
          </div>
          <div>
            <Text style={{ fontSize: '12px', color: '#666', display: 'block', marginBottom: '4px' }}>高度</Text>
            <InputNumber
              value={component.style.height}
              onChange={(value) => handleUpdate('style.height', value)}
              style={{ width: '100%' }}
              size="small"
            />
          </div>
        </div>
      </div>

      <Divider style={{ margin: '16px 0' }} />

      <div>
        <Text strong style={{ color: '#2c3e50', fontSize: '14px' }}>组件属性</Text>
        <div style={{ marginTop: '12px', display: 'flex', flexDirection: 'column', gap: '12px' }}>
          {component.type === COMPONENT_TYPES.BUTTON && (
            <>
              <div>
                <Text style={{ fontSize: '12px', color: '#666', display: 'block', marginBottom: '4px' }}>按钮文本</Text>
                <Input
                  value={component.props.text}
                  onChange={(e) => handleUpdate('props.text', e.target.value)}
                  size="small"
                />
              </div>
              <div>
                <Text style={{ fontSize: '12px', color: '#666', display: 'block', marginBottom: '4px' }}>按钮类型</Text>
                <Select
                  value={component.props.type}
                  onChange={(value) => handleUpdate('props.type', value)}
                  style={{ width: '100%' }}
                  size="small"
                >
                  <Option value="primary">主要</Option>
                  <Option value="default">默认</Option>
                  <Option value="dashed">虚线</Option>
                  <Option value="link">链接</Option>
                </Select>
              </div>
            </>
          )}

          {component.type === COMPONENT_TYPES.INPUT && (
            <>
              <div>
                <Text style={{ fontSize: '12px', color: '#666', display: 'block', marginBottom: '4px' }}>占位符</Text>
                <Input
                  value={component.props.placeholder}
                  onChange={(e) => handleUpdate('props.placeholder', e.target.value)}
                  size="small"
                />
              </div>
              <div>
                <Text style={{ fontSize: '12px', color: '#666', display: 'block', marginBottom: '4px' }}>默认值</Text>
                <Input
                  value={component.props.value}
                  onChange={(e) => handleUpdate('props.value', e.target.value)}
                  size="small"
                />
              </div>
            </>
          )}

          {component.type === COMPONENT_TYPES.TEXT && (
            <>
              <div>
                <Text style={{ fontSize: '12px', color: '#666', display: 'block', marginBottom: '4px' }}>文本内容</Text>
                <Input
                  value={component.props.text}
                  onChange={(e) => handleUpdate('props.text', e.target.value)}
                  size="small"
                />
              </div>
              <div>
                <Text style={{ fontSize: '12px', color: '#666', display: 'block', marginBottom: '4px' }}>标题级别</Text>
                <Select
                  value={component.props.level}
                  onChange={(value) => handleUpdate('props.level', value)}
                  style={{ width: '100%' }}
                  size="small"
                >
                  <Option value={1}>H1</Option>
                  <Option value={2}>H2</Option>
                  <Option value={3}>H3</Option>
                  <Option value={4}>H4</Option>
                  <Option value={5}>H5</Option>
                </Select>
              </div>
            </>
          )}

          {component.type === COMPONENT_TYPES.CARD && (
            <>
              <div>
                <Text style={{ fontSize: '12px', color: '#666', display: 'block', marginBottom: '4px' }}>卡片标题</Text>
                <Input
                  value={component.props.title}
                  onChange={(e) => handleUpdate('props.title', e.target.value)}
                  size="small"
                />
              </div>
              <div>
                <Text style={{ fontSize: '12px', color: '#666', display: 'block', marginBottom: '4px' }}>卡片内容</Text>
                <Input.TextArea
                  value={component.props.content}
                  onChange={(e) => handleUpdate('props.content', e.target.value)}
                  rows={3}
                  size="small"
                />
              </div>
            </>
          )}

          {component.type === COMPONENT_TYPES.SWITCH && (
            <div>
              <Text style={{ fontSize: '12px', color: '#666', display: 'block', marginBottom: '8px' }}>默认状态</Text>
              <Switch
                checked={component.props.checked}
                onChange={(checked) => handleUpdate('props.checked', checked)}
                size="small"
              />
            </div>
          )}

          {component.type === COMPONENT_TYPES.SLIDER && (
            <>
              <div>
                <Text style={{ fontSize: '12px', color: '#666', display: 'block', marginBottom: '4px' }}>最小值</Text>
                <InputNumber
                  value={component.props.min}
                  onChange={(value) => handleUpdate('props.min', value)}
                  style={{ width: '100%' }}
                  size="small"
                />
              </div>
              <div>
                <Text style={{ fontSize: '12px', color: '#666', display: 'block', marginBottom: '4px' }}>最大值</Text>
                <InputNumber
                  value={component.props.max}
                  onChange={(value) => handleUpdate('props.max', value)}
                  style={{ width: '100%' }}
                  size="small"
                />
              </div>
              <div>
                <Text style={{ fontSize: '12px', color: '#666', display: 'block', marginBottom: '4px' }}>当前值</Text>
                <InputNumber
                  value={component.props.value}
                  onChange={(value) => handleUpdate('props.value', value)}
                  style={{ width: '100%' }}
                  size="small"
                />
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
};

// 画布区域
const Canvas = () => {
  const [isDragging, setIsDragging] = useState(false);
  const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });
  const canvasRef = useRef(null);
  const { components, selectedComponent, addComponent, selectComponent, updateComponent, deleteComponent, duplicateComponent } = useStore();
  // 添加鼠标事件处理
  const handleMouseDown = (e, component) => {
    if (selectedComponent?.id === component.id) {
      setIsDragging(true);
      const rect = canvasRef.current.getBoundingClientRect();
      setDragOffset({
        x: e.clientX - rect.left - component.style.left,
        y: e.clientY - rect.top - component.style.top
      });
    }
  };

  // 添加鼠标移动和释放事件监听
  useEffect(() => {
    const handleMouseMove = (e) => {
      if (isDragging && selectedComponent) {
        const rect = canvasRef.current.getBoundingClientRect();
        const newLeft = e.clientX - rect.left - dragOffset.x;
        const newTop = e.clientY - rect.top - dragOffset.y;

        updateComponent(selectedComponent.id, {
          style: {
            ...selectedComponent.style,
            left: Math.max(0, newLeft),
            top: Math.max(0, newTop)
          }
        });
      }
    };

    const handleMouseUp = () => {
      setIsDragging(false);
    };

    if (isDragging) {
      document.addEventListener('mousemove', handleMouseMove);
      document.addEventListener('mouseup', handleMouseUp);
    }
    const handleKeyDown = (e) => {
      if (selectedComponent) {
        switch (e.key) {
          case 'Delete':
            deleteComponent(selectedComponent.id);
            break;
          case 'c':
            if (e.ctrlKey) {
              duplicateComponent(selectedComponent.id);
            }
            break;
          case 'ArrowUp':
            e.preventDefault();
            updateComponent(selectedComponent.id, {
              style: { ...selectedComponent.style, top: selectedComponent.style.top - 1 }
            });
            break;
          // 添加其他方向键
        }
      }
    };

    return () => {
      document.removeEventListener('mousemove', handleMouseMove);
      document.removeEventListener('mouseup', handleMouseUp);
      document.removeEventListener('keydown', handleKeyDown);
    };
  }, [isDragging, selectedComponent, dragOffset, updateComponent, , deleteComponent, duplicateComponent]);

  const [{ isOver }, drop] = useDrop(() => ({
    accept: 'component',
    drop: (item, monitor) => {
      const offset = monitor.getSourceClientOffset();
      const canvasRect = canvasRef.current.getBoundingClientRect();

      const x = Math.max(0, offset.x - canvasRect.left);
      const y = Math.max(0, offset.y - canvasRect.top);

      addComponent({
        type: item.type,
        props: { ...item.defaultProps },
        style: { ...item.style },
        x,
        y
      });
    },
    collect: (monitor) => ({
      isOver: monitor.isOver(),
    }),
  }));

  const handleCanvasClick = (e) => {
    if (e.target === canvasRef.current) {
      selectComponent(null);
    }
  };

  return (
    <div
      ref={(node) => {
        canvasRef.current = node;
        drop(node);
      }}
      style={{
        width: '100%',
        height: '100%',
        background: isOver
          ? 'linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%)'
          : 'linear-gradient(135deg, #f8f9ff 0%, #ffffff 100%)',
        position: 'relative',
        overflow: 'hidden',
        border: isOver ? '2px dashed #667eea' : '1px solid #e8e8e8',
        borderRadius: '8px',
        transition: 'all 0.3s ease'
      }}
      onClick={handleCanvasClick}
    >
      {components.map((component) =>
        renderComponent(
          component,
          selectedComponent?.id === component.id,
          selectComponent
        )
      )}

      {components.length === 0 && (
        <div style={{
          position: 'absolute',
          top: '50%',
          left: '50%',
          transform: 'translate(-50%, -50%)',
          textAlign: 'center',
          color: '#999'
        }}>
          <LayoutOutlined style={{ fontSize: '48px', color: '#d9d9d9', marginBottom: '16px' }} />
          <Text style={{ color: '#999' }}>拖拽组件到这里开始设计</Text>
        </div>
      )}
    </div>
  );
};

// 顶部工具栏
const TopToolbar = () => {
  const { selectedComponent, deleteComponent, duplicateComponent, clearCanvas, components } = useStore();
  const [previewVisible, setPreviewVisible] = useState(false);
  const [codeVisible, setCodeVisible] = useState(false);

  const handleDelete = () => {
    if (selectedComponent) {
      deleteComponent(selectedComponent.id);
      message.success('组件已删除');
    }
  };

  const handleDuplicate = () => {
    if (selectedComponent) {
      duplicateComponent(selectedComponent.id);
      message.success('组件已复制');
    }
  };

  const handleClear = () => {
    Modal.confirm({
      title: '确认清空画布',
      content: '这将删除所有组件，此操作不可恢复。',
      onOk: () => {
        clearCanvas();
        message.success('画布已清空');
      }
    });
  };

  const generateCode = () => {
    const imports = new Set(['React']);
    const components_code = components.map(comp => {
      switch (comp.type) {
        case COMPONENT_TYPES.BUTTON:
          imports.add('Button');
          return `<Button type="${comp.props.type}" style={{position: 'absolute', left: ${comp.style.left}, top: ${comp.style.top}, width: ${comp.style.width}, height: ${comp.style.height}}}>${comp.props.text}</Button>`;
        case COMPONENT_TYPES.INPUT:
          imports.add('Input');
          return `<Input placeholder="${comp.props.placeholder}" value="${comp.props.value}" style={{position: 'absolute', left: ${comp.style.left}, top: ${comp.style.top}, width: ${comp.style.width}, height: ${comp.style.height}}} />`;
        case COMPONENT_TYPES.TEXT:
          imports.add('Typography');
          return `<Typography.Title level={${comp.props.level}} style={{position: 'absolute', left: ${comp.style.left}, top: ${comp.style.top}, margin: 0}}>${comp.props.text}</Typography.Title>`;
        case COMPONENT_TYPES.CARD:
          imports.add('Card');
          return `<Card title="${comp.props.title}" style={{position: 'absolute', left: ${comp.style.left}, top: ${comp.style.top}, width: ${comp.style.width}, height: ${comp.style.height}}}>${comp.props.content}</Card>`;
        case COMPONENT_TYPES.SWITCH:
          imports.add('Switch');
          return `<Switch checked={${comp.props.checked}} style={{position: 'absolute', left: ${comp.style.left}, top: ${comp.style.top}}} />`;
        case COMPONENT_TYPES.SLIDER:
          imports.add('Slider');
          return `<Slider min={${comp.props.min}} max={${comp.props.max}} value={${comp.props.value}} style={{position: 'absolute', left: ${comp.style.left}, top: ${comp.style.top}, width: ${comp.style.width}}} />`;
        default:
          return '';
      }
    });

    const importStatement = `import React from 'react';\nimport { ${Array.from(imports).filter(i => i !== 'React').join(', ')} } from 'antd';`;
    const componentCode = `
${importStatement}

const GeneratedComponent = () => {
  return (
    <div style={{position: 'relative', width: '100%', height: '600px', background: '#f5f5f5'}}>
      ${components_code.join('\n      ')}
    </div>
  );
};

export default GeneratedComponent;`;

    return componentCode;
  };

  return (
    <>
      <div style={{
        height: '60px',
        background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
        padding: '0 24px',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
        borderRadius: '0 0 8px 8px'
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
          <Title level={3} style={{
            margin: 0,
            color: 'white',
            fontWeight: 600
          }}>
            <AppstoreOutlined style={{ marginRight: '8px' }} />
            低代码开发平台
          </Title>
        </div>

        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
          <Button
            icon={<CopyOutlined />}
            disabled={!selectedComponent}
            onClick={handleDuplicate}
            ghost
            size="small"
            style={{ color: 'white', borderColor: 'white' }}
          >
            复制
          </Button>

          <Button
            icon={<DeleteOutlined />}
            disabled={!selectedComponent}
            onClick={handleDelete}
            ghost
            size="small"
            style={{ color: 'white', borderColor: 'white' }}
          >
            删除
          </Button>

          <Button
            icon={<EyeOutlined />}
            onClick={() => setPreviewVisible(true)}
            ghost
            size="small"
            style={{ color: 'white', borderColor: 'white' }}
          >
            预览
          </Button>

          <Button
            icon={<CodeOutlined />}
            onClick={() => setCodeVisible(true)}
            ghost
            size="small"
            style={{ color: 'white', borderColor: 'white' }}
          >
            代码
          </Button>

          <Button
            onClick={handleClear}
            disabled={components.length === 0}
            ghost
            size="small"
            style={{ color: 'white', borderColor: 'white' }}
          >
            清空
          </Button>
        </div>
      </div>

      <Modal
        title="预览效果"
        open={previewVisible}
        onCancel={() => setPreviewVisible(false)}
        footer={null}
        width={900}
        style={{ top: 20 }}
      >
        <div style={{
          position: 'relative',
          background: 'linear-gradient(135deg, rgba(255, 255, 255, 0.9) 0%, rgba(248, 250, 252, 0.9) 100%)',
          height: '600px',
          borderRadius: '8px',
          overflow: 'hidden'
        }}>
          {components.map((component) =>
            renderComponent(component, false, () => { })
          )}
        </div>
      </Modal>

      <Modal
        title="生成的代码"
        open={codeVisible}
        onCancel={() => setCodeVisible(false)}
        footer={null}
        width={900}
        style={{ top: 20 }}
      >
        <pre style={{
          background: '#1a1a1a',
          color: '#f8f8f2',
          padding: '20px',
          borderRadius: '8px',
          fontSize: '13px',
          lineHeight: '1.6',
          overflow: 'auto',
          maxHeight: '500px',
          fontFamily: 'Consolas, monospace'
        }}>
          {generateCode()}
        </pre>
      </Modal>
    </>
  );
};

// 主应用
const LowCodePlatform = () => {
  const { selectedComponent, updateComponent } = useStore();

  return (
    <DndProvider backend={HTML5Backend}>
      <div style={{
        width: '100vw',
        height: '100vh',
        display: 'flex',
        flexDirection: 'column',
        background: '#f5f5f5'
      }}>
        {/* 顶部工具栏 */}
        <TopToolbar />

        {/* 主要内容区域 */}
        <div style={{
          flex: 1,
          display: 'flex',
          overflow: 'hidden'
        }}>
          {/* 左侧物料区 */}
          {/* 左侧物料区 */}
          <div style={{
            width: '280px',
            backgroundColor: '#fff',
            borderRight: '1px solid #e8e8e8',
            display: 'flex',
            flexDirection: 'column'
          }}>
            <div style={{
              padding: '16px',
              borderBottom: '1px solid #f0f0f0',
              display: 'flex',
              alignItems: 'center'
            }}>
              <AppstoreOutlined style={{ fontSize: '20px', color: '#667eea', marginRight: '12px' }} />
              <Title level={5} style={{ margin: 0, color: '#333' }}>
                组件库
              </Title>
            </div>
            <div style={{
              flex: 1,
              overflowY: 'auto',
              padding: '16px'
            }}>
              <ComponentList />
            </div>
          </div>

          {/* 中间画布区 */}
          <div style={{
            flex: 1,
            padding: '24px',
            overflow: 'auto'
          }}>
            <Canvas />
          </div>

          {/* 右侧属性编辑区 */}
          <div style={{
            width: '300px',
            backgroundColor: '#fff',
            borderLeft: '1px solid #e8e8e8',
            display: 'flex',
            flexDirection: 'column'
          }}>
            <div style={{
              padding: '16px',
              borderBottom: '1px solid #f0f0f0',
              display: 'flex',
              alignItems: 'center'
            }}>
              <SettingOutlined style={{ fontSize: '20px', color: '#667eea', marginRight: '12px' }} />
              <Title level={5} style={{ margin: 0, color: '#333' }}>
                属性编辑
              </Title>
            </div>
            <div style={{
              flex: 1,
              overflowY: 'auto',
              padding: '16px'
            }}>
              <PropertyEditor
                component={selectedComponent}
                onUpdate={updateComponent}
              />
            </div>
          </div>
        </div>
      </div>
    </DndProvider>
  );
};

// 组件列表
const ComponentList = () => {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
      {ComponentLibrary.map((component) => (
        <DragItem key={component.type} component={component} />
      ))}
    </div>
  );
};

export default LowCodePlatform;